package com.test.nacos.conf;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>Description:  nacos配置自动更新测试，修改nacos上配置，将自动读取到内存替换最新值</p>
 *
 * @author zhuyoulong
 * @date 2020-12-25
 */
@RestController
@RequestMapping("/config")
@Slf4j
//@RefreshScope
@NacosPropertySource(dataId = "nacos.cfg.dataId", autoRefreshed = true)
public class NacosConfigController {

    @NacosInjected
    private ConfigService configService;

    /**
     *在nacos配置服务中nacos.cfg.dataId的值要配置成：useLocalCache=false
     */
    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;

    /**
     * 获取配置
     * @return
     */
    @RequestMapping(value = "/get",method = RequestMethod.GET)
    public String getConfig(){

        log.info("useLocalCache={}",useLocalCache);

        String dataId = "nacos.cfg.dataId";
        String defaultGroup = "DEFAULT_GROUP";
        long timeOutms = 1000;
        try {
            return configService.getConfig(dataId,defaultGroup,timeOutms);
        } catch (NacosException e) {
            log.error("获取配置异常",e);
        }
        return null;
    }

}
